/**
 * 组织架构 js
 */
var showRemove = false;
var showRename= false;
var organization = {
	curPage : 1,
	pageSize : 8,
	dataCache : null,
	startEvent : function() {
		organization.getAllResource();

		comValidform = $(".com-addForm").Validform({
			tiptype : 2,
			tipSweep : true,
			beforeSubmit : function(curform) {
				var parentId = organization.getSelData();
				if (parentId != null) {
					$('.com-addForm input[name="parentId"]').val(parentId);
				}
			}
		});
	},
	// 查询版本信息
	search : function() {
		// var type=$.trim($('#searchModForm input[name="type"]').val());
		// var ver=$.trim($('#searchModForm input[name="ver"]').val());
		organization.getAllResource();
		organization.showTreeData();
	},
	getAllResource : function() {
		// 获取所有资源
		var url = 'mgr/OrganizationCtrl/listAllByUser';

		if (typeof (pageIdx) != "undefined") {
			organization.curPage = pageIdx;
		}

		var params = {
			actUserId:userId
		};

		var cb = function(data) {
			//console.trace("data code = " & data.resultCode);
			if (data.resultCode == 200) {
				organization.dataCache = data.result;
			}
		};
		sendApiNoLoadSync(url, params, cb, 'POST');
	},

	setCheck : function() {
		var zTree = $.fn.zTree.getZTreeObj("orgTree"), py = "", sy = "s", pn = "", sn = "s", type = {
			"Y" : py + sy,
			"N" : pn + sn
		};
		zTree.setting.check.chkboxType = type;
	},

	bindEvent : function() {
		$('#updateData').unbind();
		$('#updateData').on('click',
		function() {
			var thisObj = $(this);
			var id = $("#changeID").html();
			var name = $("#changeName").html();
			var type = $("#changeType").val();
			if (type != "") {
				art.dialog.data('id', id);
				art.dialog.data('name', name);
				var path = APP_ADDRESS
						+ 'mgr/sysMgr/organization/organizationUpdate.jsp';
				art.dialog.open(path,
				{
					title : '修改名称',
					width : 400,
					height : 300,
					ok : function() {
						var returnStatus = this.iframe.contentWindow
								.submitForm();
						if (returnStatus) {
							organization
									.search();
						}
						return false;
					},
					cancel : true
				});
			} else {
				alert("请先选中一个节点！")
			}

		});
		$('#deleteData').unbind();
		$('#deleteData').on('click', function() {

			var thisObj = $(this);
			var id = $("#changeID").html();
			var type = $("#changeType").val();
			if (type != "") {
				if (type != 5) {
					var content = "你确认删除-" + $("#changeName").html() + " ?";
					art.dialog.confirm(content, function() {

						var url = 'mgr/OrganizationCtrl/delete';
						var params = {
							'id' : id
						};

						params.actUserId=userId;
						if(params.actUserId == ''){
							alert("登录超时，请重新登录后重试");
							return false;
						}

						var cb = function(data) {
							alert(data.msg);
							organization.search();
							$("#changeID").html(null);
							$("#changeName").html(null);
							$("#changeType").html(null);
						}
						sendApiNoLoad(url, params, cb, 'POST');
					}, function() {
					})
				} else {
					alert("系统用户不能删除，请前往系统用户更改用户的组织架构！");
				}
			} else {
				alert("请先选中一个节点！")
			}

		});

		$('#lookData').unbind();
		$('#lookData').on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find('input[name="id"]')
							.eq(0).val();
					art.dialog.data('id', id);
					var path = APP_ADDRESS
							+ 'mgr/sysMgr/organization/organizationLook.jsp';
					art.dialog.open(path, {
						title : '查看',
						width : 600,
						height : 450,
						cancel : true
					});
				});
		// 查询
		$('#searchData').click(function() {
			organization.curPage = 1;
			organization.setPageChange(null);
			organization.search();
		});
		$('#excel').on('click', function() { 
			var url = '../../../mgr/OrganizationCtrl/excel';
			location.href = url;   
		});
		$('#addData').on(
				'click',
				function() {
					var path = APP_ADDRESS
							+ 'mgr/sysMgr/organization/organizationAdd.jsp';
					art.dialog.open(path, {
						title : '添加',
						width : 700,
						height : 500,
						ok : function() {
							var returnStatus = this.iframe.contentWindow
									.submitForm();
							if (returnStatus) {
								organization.search();
							}
							return false;
						},
						cancel : true
					});
				});
	},
	showTreeData : function() {

		var setting = {
			check : {
				enable : true,
				chkStyle : "radio",
				radioType : "all"
			},
			data : {
				simpleData : {
					enable : true
				}
			},

			view: {
				addHoverDom: addHoverDom,
				removeHoverDom: removeHoverDom,
				nameIsHTML : true
			},


			callback : {
				onCheck : zTreeOnClick,

				beforeRename:zTreeBeforeRename,

				onRename: zTreeOnRename,

				beforeRemove: zTreeBeforeRemove,

				onRemove:zTreeOnRemove
			},

			edit:{
				drag:{
					isCopy:false,
					isMove:false,
				},
				enable:true,
				removeTitle:"冻结",
				renameTitle:"修改名称",
				showRemoveBtn: showRemove,
				showRenameBtn: showRename
			}
		};
		var zNodes = [];
		var dataCache = organization.dataCache;
		
		
		for (var i = 0; i < dataCache.length; i++) {
			
			var newid = dataCache[i].id;
			
			if(dataCache[i].orgType == 5 ){
				newid = i + 100
			}
			
			zNodes[i] = {
				id : newid,
				name : dataCache[i].name,
				pId : dataCache[i].parentID,
				orgType : dataCache[i].orgType
			}
			
			
			if (i == 0) {
				zNodes[i].open = true;
			}
		}
		$.fn.zTree.init($("#orgTree"), setting, zNodes);
		organization.setCheck();
		$("#py").bind("change", organization.setCheck());
		$("#sy").bind("change", organization.setCheck());
		$("#pn").bind("change", organization.setCheck());
		$("#sn").bind("change", organization.setCheck());
	},

	// 选择返回事件
	getSelData : function() {
		var zTree = $.fn.zTree.getZTreeObj("orgTree");
		var nodes = zTree.getCheckedNodes(); // 取得所有选中的
		var len = nodes.length;
		if (len != 1) {
			return null;
		}
		return nodes[0].id;
	},
	init : function() {
		organization.startEvent();
		if (organization.dataCache != null) {
			organization.showTreeData();
		}

		organization.bindEvent();
		jsUtils.controlFunctionBtn();
	}
};

$(document).ready(function() {

	if(funcBtns.indexOf('organization_96') >=0){
		showRename = true;
	}

	if(funcBtns.indexOf('organization_97') >=0){
		showRemove = true;
	}

	organization.init();

});

function zTreeOnClick(event, treeId, treeNode) {
	$("#changeName").html(treeNode.name);
	$("#changeID").html(treeNode.id);
	$("#changeType").val(treeNode.orgType);
};

function zTreeBeforeEditName(treeId, treeNode) {

	return ture;
}

// isShowRenameBtn，是否显示重命名按钮
function isShowRenameBtn(treeId, treeNode) {
	var result = false;
	if(funcBtns.indexOf('organization_96') >=0){
		result = true;
	}
	alert(" 编辑名称: " + result);
	return result;
}

// isShowRemoveBtn，是否显示移除按钮
function isShowRemoveBtn(treeId, treeNode) {
	var result = false;
	if(funcBtns.indexOf('organization_97') >=0){
		result = true;
	}
	alert("删除节点: " + result);
	return result;
}

function zTreeBeforeRename(treeId, treeNode, newName, isCancel) {

	art.dialog.confirm('你确认要将名称修改为：' + newName + '？', function(){
		var url = 'mgr/OrganizationCtrl/updateName';
		var params = {
			'id':treeNode.id,
			'newName':newName
		};

		params.actUserId=userId;
		if(params.actUserId == null || params.actUserId == ''){
			console.log(params.actUserId)
			alert("登录超时，请重新登录后重试");
			return false;
		}

		var cb = function(data){
			alert(data.msg);
		}
		sendApiNoLoad(url, params, cb, 'POST');
	}, function(){

	});

	return true;
}

function zTreeOnRename(event, treeId, treeNode, isCancel) {

}

function zTreeOnRemove(event, treeId, treeNode) {

}

function zTreeBeforeRemove(treeId, treeNode) {

	var str = "你确认要删除该部门吗？" + "\n\n部门名称为:"+ treeNode.name;
	if(treeNode.orgType == 4){
		str = "你确认要删除该职务吗？" + "\n\n职务名称为:"+ treeNode.name;
	}

	var result=window.confirm(str);
	if(result){
		var result = false;
		var url = 'mgr/OrganizationCtrl/delete';
		var params = {
			'id':treeNode.id,
			'actUserId':userId
		};
		var cb = function(data) {
			alert(data.msg);
			if (data.resultCode != 200) {
				result = false;
			} else {
				result = true;
			}
		}
		sendApiNoLoadSync(url, params, cb, 'POST');
	}

	return result;
}

function addHoverDom(treeId, treeNode) {
	var aObj = $("#" + treeNode.tId + "_a");
	if ($("#diyBtn_"+treeNode.id).length>0) return;

	if(treeNode.orgType == 4) return;

	var editStr = "<span id='diyBtn_space_" +treeNode.id+ "' > </span>" + "<a type='button' name='organization_98'  class='diyBtn1 btn btn-default btn-xs ' id='diyBtn_" + treeNode.id + "' title='"+treeNode.name+"' style='margin-left: 5px; margin-right: 5px; background:#449d44;display:none;' onfocus='this.blur();'>添加</a>";
	aObj.append(editStr);
	var btn = $("#diyBtn_"+treeNode.id);
	if (btn) btn.bind("click", function(){
		var path = APP_ADDRESS
			+ 'mgr/sysMgr/organization/organizationAdd02.jsp';
		art.dialog.data('orgType', treeNode.orgType);
		art.dialog.data('parentID', treeNode.id);
		art.dialog.data('parName', treeNode.name);
		art.dialog.open(path, {
			title : '添加',
			width : 700,
			height : 300,
			ok : function() {
				var returnStatus = this.iframe.contentWindow
					.submitForm();
				if (returnStatus) {
					organization.search();
					art.dialog.close();
				}
				return returnStatus;
			},
			cancel : true
		});
	});

	jsUtils.controlFunctionBtn();
};

function removeHoverDom(treeId, treeNode) {
	$("#diyBtn_"+treeNode.id).unbind().remove();

	$("#diyBtn_space_" +treeNode.id).unbind().remove();
};


